package com.zyx.camunda.config;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author zyx
 * @since 2023/10/8 14:34
 */
public class RestTemplateConfig {

    @Bean("baseRestTemplate")
    public RestTemplate baseRestTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        // 支持中文编码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
        // 最大连接数
        poolingConnectionManager.setMaxTotal(1000);
        // 单路由并发数
        poolingConnectionManager.setDefaultMaxPerRoute(200);

        HttpClient httpClient = HttpClients.custom()
            .setConnectionManager(poolingConnectionManager)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
            .build();

        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        // 单位为ms
        clientHttpRequestFactory.setReadTimeout(5000);
        // 单位为ms
        clientHttpRequestFactory.setConnectTimeout(2000);
        return clientHttpRequestFactory;
    }

}
